﻿using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZhonTai.Admin.Core.Dto;
using ZhonTai.Admin.Services;
using ZhonTai.DynamicApi;
using ZhonTai.DynamicApi.Attributes;
using ZhonTai.Industry.Core.Consts;
using ZhonTai.Industry.Core.Enums;
using ZhonTai.Industry.Domain.FormulaDetail;
using ZhonTai.Industry.Services.FormulaDetail.Dto.Input;
using ZhonTai.Industry.Services.FormulaDetail.Dto.Output;

namespace ZhonTai.Industry.Services.FormulaDetail
{
    /// <summary>
    /// 配方详情详情服务
    /// </summary>
    [Order(20)]
    [DynamicApi(Area = IndustryConsts.AreaName)]
    public class FormulaDetailService : BaseService, IFormulaDetatilService, IDynamicApi
    {
        private readonly IFormulaDetailRepository _formulaDetailRepository;

        public FormulaDetailService(IFormulaDetailRepository formulaDetailRepository)
        {
            _formulaDetailRepository = formulaDetailRepository;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<FormulaDetailGetOutput> GetAsync(long id)
        {
            return await _formulaDetailRepository.Select
                 .WhereDynamic(id)
                 .Include(x => x.WorkStation)
                 .ToOneAsync(t =>
                 new FormulaDetailGetListOutput
                 {
                     StationCode = t.WorkStation.StationCode,
                     StationName = t.WorkStation.StationName,
                     ByteOffset = t.PLCOffset.ByteOffset,
                     PLCDataType = t.PLCOffset.DataType,
                 });
        }

        /// <summary>
        /// 列表查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IEnumerable<FormulaDetailGetListOutput>> GetListAsync(FormulaDetailGetListInput input)
        {
            var list = await _formulaDetailRepository.Select
                .OrderBy(a => a.Sort)
                .ToListAsync(t =>
                new FormulaDetailGetListOutput
                {
                    StationCode = t.WorkStation.StationCode,
                    StationName = t.WorkStation.StationName,
                    ByteOffset = t.PLCOffset.ByteOffset,
                    PLCDataType = t.PLCOffset.DataType,
                });
            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<PageOutput<FormulaDetailGetPageOutput>> GetPageAsync(PageInput<FormulaDetailGetPageInput> input)
        {
            var filter = input.Filter;
            var select = _formulaDetailRepository.Select
                .WhereDynamicFilter(input.DynamicFilter)
                .WhereIf(filter.DeviceFormulaId.HasValue && filter.DeviceFormulaId > 0, w => w.DeviceFormulaId == filter.DeviceFormulaId)
                .Count(out var total);
            if (input.SortList != null && input.SortList.Count > 0)
            {
                input.SortList.ForEach(sort =>
                {
                    select = select.OrderByPropertyNameIf(sort.Order.HasValue, sort.PropName, sort.IsAscending.Value);
                });
            }
            else
            {
                select = select.OrderBy(a => a.Sort);
            }
            var list = await select
            .Page(input.CurrentPage, input.PageSize)
            .ToListAsync(t =>
            new FormulaDetailGetPageOutput
            {
                StationCode = t.WorkStation.StationCode,
                StationName = t.WorkStation.StationName,
                ByteOffset = t.PLCOffset.ByteOffset,
                PLCDataType = t.PLCOffset.DataType,
            });
            var data = new PageOutput<FormulaDetailGetPageOutput>()
            {
                List = list,
                Total = total
            };
            return data;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<long> AddAsync(FormulaDetailAddInput input)
        {
            var entity = Mapper.Map<FormulaDetailEntity>(input);
            entity.Enabled = true;
            var id = (await _formulaDetailRepository.InsertAsync(entity)).Id;
            return id;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task UpdateAsync(FormulaDetailUpdateInput input)
        {
            var entity = await _formulaDetailRepository.GetAsync(input.Id);
            if (!(entity?.Id > 0))
            {
                throw ResultOutput.Exception("配方详情不存在！");
            }

            Mapper.Map(input, entity);
            await _formulaDetailRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> DeleteAsync(long id)
        {
            return await _formulaDetailRepository.DeleteAsync(id) > 0;
        }

        /// <summary>
        /// 软删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<bool> SoftDeleteAsync(long id)
        {
            return await _formulaDetailRepository.SoftDeleteAsync(id);
        }

        /// <summary>
        /// 批量软删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPut]
        public async Task<bool> BatchSoftDeleteAsync(long[] ids)
        {
            return await _formulaDetailRepository.SoftDeleteAsync(ids);
        }

        /// <summary>
        /// 设置启用
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task SetEnableAsync(FormulaDetailSetEnableInput input)
        {
            var entity = await _formulaDetailRepository.GetAsync(input.FormulaDetailId);
            entity.Enabled = input.Enabled;
            await _formulaDetailRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 设备详情配方复制
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task CopyDetailForOtherStationAsync(FormulaDetailCopyStatiionInput input)
        {
            var details = await _formulaDetailRepository.Select
         .Where(w => w.StationId == input.CopyStationId)
         .ToListAsync();
            var insertList = new List<FormulaDetailEntity>();
            foreach (var stationId in input.StationIds)
            {
                var newDetails = details.Select(d => new FormulaDetailEntity
                {
                    StationId = stationId,
                    OffsetId = d.OffsetId,
                    ParamKey = d.ParamKey,
                    ParamValue = d.ParamValue,
                    Enabled = d.Enabled,
                    Sort = d.Sort,
                    DeviceFormulaId = d.DeviceFormulaId,
                });

                insertList.AddRange(newDetails);
            }
            await _formulaDetailRepository.InsertAsync(insertList);
        }
    }
}